
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;

/**
 * Servlet implementation class CreateHostUser
 */
@WebServlet("/CreateHostUser")
public class CreateHostUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateHostUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("userName");
		String pwd = request.getParameter("pwd");
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		int sexType = Integer.parseInt(request.getParameter("sex"));
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date birthdayDate = new Date();
		try {
			birthdayDate = dateFormat.parse(request.getParameter("birthday"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Timestamp birthday = new Timestamp(birthdayDate.getTime());
		String phoneNumber = request.getParameter("phoneNumber");
		String email = request.getParameter("email");
		//check account exits
		if(checkAccountExited(name))
		{
			response.sendRedirect("error.html");
		}
		else if (checkEmailExited(email))
		{
			response.sendRedirect("error.html");
		}
		else
		{
		PrintWriter out = response.getWriter();
		hostUser hostUserObj = new hostUser();
		hostUserObj.setAccount(name);
		hostUserObj.setPassword(pwd);
		hostUserObj.setFirstName(firstName);
		hostUserObj.setLastName(lastName);
		hostUserObj.setSexType(sexType);
		hostUserObj.setBirthday(birthday);
		hostUserObj.setPhoneNumber(phoneNumber);
		hostUserObj.setEmailAddress(email);
		hostUserObj.setUserType(2);
		hostUserObj.setIsPhoneValidated(1);
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	        session.beginTransaction();
	        session.saveOrUpdate(hostUserObj);
	        session.getTransaction().commit();
			} catch(Exception ex){
				HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
			}
		response.sendRedirect("Success.html");
		}
	}
	protected boolean checkAccountExited(String x_userName)
	{
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        String sqlString = "select * from hostusers where account = '" + x_userName + "'";
		Query queryResult = session.createSQLQuery(sqlString).addEntity(hostUser.class);
	    String sqlString2 = "select * from guestusers where account = '" + x_userName + "'";
        Query queryResult2 = session.createSQLQuery(sqlString2).addEntity(guestUser.class);
	    if(queryResult.list().isEmpty() && queryResult2.list().isEmpty())
	    {
	        session.getTransaction().commit();
	    	return false;
	    }
	    else
	    {
	        session.getTransaction().commit();
	    	return true;
	    }
		} catch(Exception ex){
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
		}
		return true;
	}
	protected boolean checkEmailExited(String x_email)
	{
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        String sqlString = "select * from hostusers where emailAddress = '" + x_email + "'";
		Query queryResult = session.createSQLQuery(sqlString).addEntity(hostUser.class);
	    String sqlString2 = "select * from guestusers where emailAddress = '" + x_email + "'";
        Query queryResult2 = session.createSQLQuery(sqlString2).addEntity(guestUser.class);
	    if(queryResult.list().isEmpty() && queryResult2.list().isEmpty())
	    {
	        session.getTransaction().commit();
	    	return false;
	    }
	    else
	    {
	        session.getTransaction().commit();
	    	return true;
	    }
		} catch(Exception ex){
			HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
		}
		return true;
	}

}
